import React from 'react';
import ReactDOM from 'react-dom';

import './css/todoMvc.css'

import {
  Header,
  TodoList,
  Footer
} from './todoMvc';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      list: JSON.parse(localStorage.getItem('ReactTodos')) || [],
      text: ''
    }
    this.addTodo = this.addTodo.bind(this)
  }
  render() {
    return ( 
    <React.Fragment>
      <div className ='todos'>
      <Header addTodo = {this.addTodo} state = {this.state} changeAll={this.changeAll.bind(this)} ></Header> 
      <TodoList editTodo={this.editTodo.bind(this)} name = {this.state} checkItem={this.checkItem.bind(this)} removeTodo={this.removeTodo.bind(this)}></TodoList> 
      {
        true ? <Footer items = {this.state.list} statusHandler={this.statusHandler.bind(this)} clearComplete={this.clearComplete.bind(this)}></Footer> : '' 
      }
      </div> 
      </React.Fragment>
    )
  }

  addTodo(todoObj) {
    this.setState({
      list: this.state.list.concat(todoObj) || []
    },function () {
      localStorage.setItem('ReactTodos', JSON.stringify(this.state.list))

    })

  }
  changeAll(flag) {
    this.state.list.forEach(item => item.isDone = flag);
    this.setState({
      list:this.state.list
    })
  }
  checkItem(index) {
    this.state.list[index].isDone = !this.state.list[index].isDone;
    this.setState({
      list:this.state.list
    }, function () {
      localStorage.setItem('ReactTodos', JSON.stringify(this.state.list))
    })


  }
  removeTodo(index) {
    this.state.list.splice(index,1);
    this.setState({
      list:this.state.list
    },function () {
      localStorage.setItem('ReactTodos', JSON.stringify(this.state.list))
    })
  }
  statusHandler(items) {
    this.setState({
      list:items
    })
  }
  clearComplete() {
    this.setState({
      list:JSON.parse(localStorage.getItem('ReactTodos')).filter(item => !item.isDone)
    }, function () {
      localStorage.setItem('ReactTodos', JSON.stringify(this.state.list))
      this.statusHandler(JSON.parse(localStorage.getItem('ReactTodos')).filter(item => item.isDone))
    })
  }
  editTodo() {
    console.log(this.state.list)
    localStorage.setItem('ReactTodos', JSON.stringify(this.state.list))
  }
}

ReactDOM.render( 
  <App></App>,

  document.getElementById('root')
)